    # coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from twisted.internet import reactor, task
from twisted.internet.protocol import Protocol, ClientFactory
import struct
from twisted.python import log
import sys
import json
import socket
import random
import sys
import uuid
sys.path.append("../agent")
from search_file import create_games_table
from get_vnf_info import get_process_list, get_disk_info, get_mem_info, get_cpu_info, get_mac_address


log.startLogging(sys.stdout)

class EchoClient(Protocol):
    def __init__(self):
        self.command_func_dict = {
            101: self.handle_report_s,
            102: self.handle_single_chat_s,
            103: self.handle_group_chat_s,
            104: self.handle_broadcast_chat_s,
        }
        self.version = 0
        self.state = "VERIFY"
        self.phone_number = ""

    def connectionMade(self):
        log.msg("New connection", self.transport.getPeer())

    def dataReceived(self, data):
        log.msg('in dataReceived...')

        length, self.version, command_id = struct.unpack('!3I', data[:12])
        content = data[12:length]
        if self.state == "VERIFY" and command_id == 101:
            self.handle_report_s(content)
        else:
            self.handle_data(command_id, content)

    def handle_data(self, command_id, pack_data):
        self.command_func_dict[command_id](pack_data)

    def connectionLost(self, reason):
        log.msg("connection lost")

    def handle_report_s(self, pack_data):
        """
        接受上报的返回结果并处理
        """
        content = json.loads(pack_data)
        code = content.get('code')
        if code == 0:
            log.msg('上报成功，已保存数据到数据库')
        elif code == 1:
                log.msg("has same device already, please check ip correct!")
        else:
            log.msg('上报失败,请重新上报')
            reactor.stop()
        self.state = "Data"

    def handle_single_chat_s(self, pack_data):
        """
        接受单聊
        """
        content = json.loads(pack_data)
        chat_from = content.get('chat_from')
        chat_content = content.get('chat_content')
        log.msg("[单聊][%s]:%s" % (chat_from.encode('utf-8'), chat_content.encode('utf-8')))

    def handle_group_chat_s(self, pack_data):
        """
        接受组聊
        """
        content = json.loads(pack_data)
        chat_from = content.get('chat_from')
        chat_content = content.get('chat_content')
        log.msg("[组聊][%s]:%s" % (chat_from.encode('utf-8'), chat_content.encode('utf-8')))

    def handle_broadcast_chat_s(self, pack_data):
        """
        接受广播
        """
        content = json.loads(pack_data)
        chat_from = content.get('chat_from')
        chat_content = content.get('chat_content')
        log.msg("[群聊][%s]:%s" % (chat_from.encode('utf-8'), chat_content.encode('utf-8')))
        ps_list = get_process_list()
        log.msg("ps_list--->%s" %ps_list)
        content = json.dumps(dict(ps_list=ps_list))
        self.send_data(content, 4)



    def vnf_online_report(self, ip, mac, game_info):
        """
        设备上线上报，保存数据库
        """
        log.msg("ip:%s" %ip)
        #log.msg("port:%s" %port)

        content = json.dumps(dict(ip=ip, mac=mac, game_info=game_info))
        self.send_data(content, 1)

    def send_single_chat(self, chat_from, chat_to, chat_content):
        """
        发送单聊内容
        """
        content = json.dumps(dict(chat_from=chat_from, chat_to=chat_to, chat_content=chat_content))
        self.send_data(content, 2)

    def send_group_chat(self, chat_from, chat_to, chat_content):
        """
        发送组聊内容
        """
        content = json.dumps(dict(chat_from=chat_from, chat_to=chat_to, chat_content=chat_content))
        self.send_data(content, 3)

    def send_broadcast_chat(self, chat_from, chat_content):
        """
        发送群聊内容
        """
        content = json.dumps(dict(chat_from=chat_from, chat_content=chat_content))
        self.send_data(content, 4)

    def send_data(self, send_content, command_id):
        """
        发送函数
        """
        length = 12 + len(send_content)
        version = self.version
        command_id = command_id
        header = [length, version, command_id]
        header_pack = struct.pack('!3I', *header)
        self.transport.write(header_pack + send_content)
        log.msg("send_data over....")

    def send_heartbeat(self):
        """
        发送心跳包
        """
        length = 12
        version = self.version
        command_id = 5
        header = [length, version, command_id]
        header_pack = struct.pack('!3I', *header)
        self.transport.write(header_pack)


class EchoClientFactory(ClientFactory):
    def __init__(self):
        self.p = EchoClient()

    def startedConnecting(self, connector):
        log.msg("Started to connect")

    def buildProtocol(self, addr):
        log.msg("Connected.")
        return self.p

    def clientConnectionFailed(self, connector, reason):
        log.msg("Lost connection. Reason:", reason)

    def clientConnectionLost(self, connector, reason):
        log.msg("Connection failed. Reason:", reason)


if __name__ == '__main__':
    log.msg("heereer1?")

    # ip = sys.argv[1]
    # port1 = sys.argv[2]
    # port2 = sys.argv[3]


    # api = API_1_0()
    # chat_from = sys.argv[1]
    # chat_password = sys.argv[2]
    # log.msg("chat_from=%s" % chat_from)
    # log.msg("chat_password=%s" % chat_password)
    #
    # u = api.login(chat_from, chat_password)
    # token = api.token
    # log.msg("token=%s" % token)

    cf = EchoClientFactory()
    log.msg("heereer2?")
    # chat_from = sys.argv[1]
    #
    # all_phone_numbers = ['13565208554', '13764408552', '13908549618']
    # all_phone_numbers.remove(chat_from)
    # import random
    #
    #task_send_heartbeat = task.LoopingCall(cf.p.send_heartbeat)
    #task_send_heartbeat.start(2, now=False)
    #
    # reactor.callLater(3, cf.p.vnf_online_report, chat_from, token)
    # reactor.callLater(5, cf.p.send_group_chat, chat_from, all_phone_numbers, '你好,这是10秒的时候发送')
    # reactor.callLater(8, cf.p.send_group_chat, chat_from, all_phone_numbers, '你好,这是20秒的时候发送')

    local_ip =  socket.gethostbyname(socket.gethostname())
    log.msg("local_ip--->", local_ip)

    #port = str(random.randint(5900, 10000))
    #local_ip = "192.168.122.185"
    #port = "5903"

    mac = get_mac_address()
    log.msg("mac--->", mac)

    game_info = create_games_table('D:\GameForTest', ".exe")
    log.msg("game_info--->%s" %game_info)

    reactor.callLater(1, cf.p.vnf_online_report, local_ip, mac, game_info)
    #reactor.connectTCP('192.168.200.200', 8124, cf)
    reactor.connectTCP('127.0.0.1', 8124, cf)


    reactor.run()